import { createRouter, createWebHistory } from 'vue-router'
import apiClient from '@/api.ts'

// Public views
import HomeView from '../views/HomeView.vue'
import PostView from '../views/PostView.vue'

// Auth views
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'

// Admin views
import AdminLayout from '../views/admin/AdminLayout.vue'
import DashboardView from '../views/admin/DashboardView.vue'
import AdminPostsView from '../views/admin/PostsView.vue'
import PostEditorView from '../views/admin/PostEditor.vue'
import AdminSettingsView from '../views/admin/SettingsView.vue'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // Public Routes
    { path: '/', name: 'home', component: HomeView },
    { path: '/posts/:id', name: 'post', component: PostView },

    // Auth Routes
    { path: '/login', name: 'login', component: LoginView },
    { path: '/register', name: 'register', component: RegisterView, meta: { publicPage: true } },

    // Admin Routes
    {
      path: '/admin',
      component: AdminLayout,
      meta: { requiresAuth: true },
      children: [
        { path: '', redirect: '/admin/dashboard' },
        { path: 'dashboard', name: 'admin-dashboard', component: DashboardView },
        { path: 'posts', name: 'admin-posts', component: AdminPostsView },
        { path: 'posts/new', name: 'admin-post-new', component: PostEditorView },
        { path: 'posts/edit/:id', name: 'admin-post-edit', component: PostEditorView },
        { path: 'settings', name: 'admin-settings', component: AdminSettingsView }
      ]
    }
  ]
})

// Navigation Guard
// 改进后的导航守卫，以消除启动时的黑屏问题
router.beforeEach(async (to, from, next) => {
  // 规则 0: 对于公共页面（如注册页），直接放行，不进行任何检查。
  // 这确保了注册页在任何情况下都能立即渲染，消除了黑屏。
  // 安全性检查将在组件内部进行。
  if (to.meta.publicPage) {
    return next();
  }

  const token = localStorage.getItem('token');
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

  // 检查初始化状态，但不阻塞渲染
  try {
    const response = await apiClient.get('/api/status');
    const initialSetupRequired = response.data.initialSetupRequired;

    // 规则 1: 如果需要初始化，强制重定向到 /register
    // 这个检查现在是非阻塞的。即使用户短暂看到其他页面，也会被立即重定向。
    if (initialSetupRequired && to.path !== '/register') {
      return next({ path: '/register' });
    }

    // 规则 2: 如果初始化已完成，则阻止访问 /register (理论上不会到这里，因为上面有publicPage检查)
    if (!initialSetupRequired && to.path === '/register') {
      return next({ path: '/login' });
    }
  } catch (error) {
    console.error('无法连接到API，可能需要进行初始设置。导航到注册页以进行检查。', error);
    // 如果API调用失败，我们假定需要初始化，并重定向。
    if (to.path !== '/register') {
      return next({ path: '/register' });
    }
  }

  // 规则 3: 如果路由需要认证但没有token，重定向到登录页
  if (requiresAuth && !token) {
    return next({ path: '/login', query: { redirect: to.fullPath } });
  }

  // 规则 4: 如果用户已登录，阻止其访问登录页
  if (token && to.path === '/login') {
      return next({ path: '/admin/dashboard' });
  }

  // 如果所有检查都通过，则允许导航。
  next();
});

export default router
